English 中文(简体)
C++ 构建参数
原标题:C++ constructor parameters

所以今天我写了一些C++, 经过很长一段时间的中断, 一个简单的坐标系统, 我想我要一个建构器 以2个值计算, 这样我就可以写一些东西, 比如“坐标C =新的坐标( 1, 2) ” ; ; ; ; ; ; ; ; ; ; ; ”

struct Coordinates {
   int x;
   int y;

   Coordinates(int a, int b) {
      x = a;
      y = b;
   }
};

在Cygwin编译时,我得到:

$ g++ -o adventure adventure.cpp adventure.cpp:36: error: no matching function for call to `Coordinates::Coordinates() adventure.cpp:22: note: candidates are: Coordinates::Coordinates(const Coordinates&) adventure.cpp:26: note: Coordinates::Coordinates(int, int)

不知道这里出了什么问题 我找不到关于C++结构构建器的信息 有什么想法吗?

最佳回答

在您的代码( 您没有显示) 第36行中, 您正在创建此类对象, 但是您没有向构建者传递任何参数 。 唯一有效的构建者是使用两英寸或默认的复制构建者 。 要么添加一个构建者 w/ o 参数, 要么将代码修改为通过 < code> a/ code > 和 < code> b/ code > 给构建者 。

问题回答

通过写入清晰的构造器,您将禁用自动创建默认的构造器,正如 conferences coords; 中写的那样,在定义没有构建器参数的物体时,将自动创建默认的构造器。 您必须明确提供如下内容:

struct Coordinates {
  int x;
  int y;

  Coordinates(int a, int b) {
    x = a;
    y = b;
  }

  Coordinates(): x(0), y(0) {}
};

请注意,我在默认构建器中初始化了成员变量;它不是强制性的,但它是一个好主意,因为否则即使它们会随着编译器生成的构造而默认初始化,它们也会被未定义。

还请注意,我使用成员初始化器( < code>: x(0) y(0) part) 而不是在构建体中进行分配。 良好的风格,对于类对象来说,通常会提高性能,在某些情况下,它是初始化成员的唯一方法(例如,如果该成员为 < code> const 类型或没有默认构建器) 。

注意,在 C++11 中,您只需通过写入即可告诉编译器生成一个相同的默认构造器,如果没有另一个构造器,它本会生成同样的默认构造器。

Coordinates() = default;

在类别定义中。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签