您提供的代码有两个主要问题:
1. 您没有给出从struct coordto的转换struct c。
2.你不能struct coord在外面使用,class Model因为它被声明为私有的。
即使struct coord和struct c相似,编译器的通灵能力也非常有限。对于编译器来说,这两个结构是不同的,即使它们本质上是一样的。解决这个问题的一种方法是提供struct c一个适当的赋值运算符,它采用以下类型struct coord:
strutc c {
...
void operator = (const coord& rhs) { ... }
};
您必须struct coord公开更多才能在外面使用class Model。
您可以通过以下方式做到这一点:
a)struct coord在类 Model 之外声明或
b)在类 Model 内将其声明为 public
如果您执行后者,则必须使用限定名称Model::coord来访问该结构。
备注:
考虑改变方法
coord Model::get() const;
至
const coord& Model::get() const;
一个微妙的变化会产生很大的不同。struct coord这节省了堆栈上 的隐式构造。
考虑改变运营商
void c::operator = (c &rhs);
至
void c::operator = (const c& rhs);
因为赋值运算符不会改变给定的参数结构 c。
const 正确性不仅是语法糖,而且是强制性的,它提高了可读性。
所以这是我的建议:
class Model {
public:
struct coord {
int x; int y;
};
private:
coord xy;
public:
const coord& get() const { return xy; }
};
struct c {
int x; int y;
void operator = (const c &rhs) { x = rhs.x; y = rhs.y; };
void operator = (const Model::coord &rhs) { x = rhs.x; y = rhs.y; };
};