从类方法返回结构

Returning a struct from a class method

本文关键字:结构 返回 类方法      更新时间:2023-10-16

我有一个头文件,如下所示:

class Model {
 private:
  struct coord {
    int x;
    int y;
  } xy;
 public:
  ....
 coord get() const {
  return xy;
 }
};

在另一个文件中(假设模型对象存在):

struct c {
 int x;
 int y;
 void operator = (c &rhs) {
   x = rhs.x;
   y = rhs.y;
 };
} xy;
xy = ModelObject->get();

编译器抛出一个错误,指出从坐标到 c 没有已知的 covnersion。我相信这是因为它不知道坐标类型,因为它是在类标头中声明的。我可以通过在类外声明结构来解决这个问题,但我想知道是否有可能按照我的方式做,或者这通常被认为是不好的做法

您需要

一个隐式转换运算符才能Model::coord c。有关如何执行此操作的信息,我建议查看隐式转换运算符C++。

此外,当您提到"它不知道类型,因为它在类中"时,您将使用 Model::coord 作为外部世界的结构类型(只要coord是公共的,但在您当前的情况下它不是)。

您提供的代码有两个主要问题:
1.您尚未将struct coord转换为struct c
2.您不能在class Model之外使用struct coord,因为它被声明为私有。

  1. 即使struct coordstruct c相似,编译器的通灵能力也非常有限。对于编译器,即使它们执行基本相同的操作,这两个结构也是不同的。解决此问题的一种方法是给struct c一个足够的赋值运算符,该运算符采用一种struct coord

    strutc c {  
        ...  
        void operator = (const coord& rhs) { ... }  
    };  
    
  2. 您必须使struct coord更加公开才能在class Model之外使用。
    您可以通过以下方式执行此操作:
    a) 在类模型之外声明struct coord
    b) 在类模型中声明它是公开的

    如果执行后者,则必须使用限定名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; };
};  

添加一个 c 的构造函数,取一个坐标就足以使编译器进行转换。现在为什么你有 2 种不同的类型?将这个坐标类从模型中分解并在两个点上使用它们不是更好吗?