我不是C++专家,但仍然没有很好的直观把握.我认为这是一个简单的问题.我无法将具有状态的对象传递给其他对象.我宁愿避免传递指针或引用,因为一旦设置了初始化对象,我就会在紧密循环中调用它们数百万次.我想我会像Command模式一样.这是问题的核心.我的标题代码如下:
class ObjectWithState {
public:
ObjectWithState(int state) { // This constructor creates the problem!
state_ = state; // everyting works with no constructor.
}
private:
int state_;
};
class TakesObject {
public:
TakesObject(ObjectWithState obj) {
obj_ = obj;
}
private:
ObjectWithState obj_;
};
Run Code Online (Sandbox Code Playgroud)
我的main()功能如下:
int main () {
ObjectWithState some_object(1);
TakesObject takes_object(some_object);
return 0
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误(g ++):
test.h: In constructor 'TakesObject::TakesObject(ObjectWithState)':
test.h:14: error: no matching function for call to 'ObjectWithState::ObjectWithState()'
test.h:5: note: candidates are: ObjectWithState::ObjectWithState(int)
test.h:3: note: ObjectWithState::ObjectWithState(const ObjectWithState&)
Run Code Online (Sandbox Code Playgroud)
简单回答?
我不确定这是否与拷贝构造函数有关.如果是这样,我试图找到一个解决方案,使ObjectWithState的类定义非常干净和简短.该库的用户将定义许多小函数,如TakesObject函数将使用的函数.理想情况下,ObjectsWithState的程序员只需要专注于实现一个简单的对象.也许我会误入歧途......
您可能想要做的是使用成员初始化语法:
class TakesObject {
public:
TakesObject(ObjectWithState obj): obj_(obj) {
}
private:
ObjectWithState obj_;
};
Run Code Online (Sandbox Code Playgroud)
在您发布的代码中,TakesObject构造函数将首先尝试ObjectWithState使用其默认构造函数构造new ,然后调用赋值运算符以将传入的内容复制obj到obj_.上面的示例obj_使用其复制构造函数直接构造.
您还需要为您的ObjectWithState类定义一个复制构造函数:
class ObjectWithState {
public:
ObjectWithState(int state) {
state_ = state;
}
ObjectWithState(const ObjectWithState &rhs) {
state_ = rhs.state_;
}
private:
int state_;
};
Run Code Online (Sandbox Code Playgroud)
如果省略类声明中的所有构造函数,则编译器会为您提供默认构造函数和复制构造函数.如果声明任何构造函数,则编译器不提供默认或复制构造函数,因此您必须实现自己的构造函数.