2

我有一个带有静态变量的类层次结构:

class Shape{
public:
    static string name;
}

class Rectangle: public Shape{

}

我想name根据班级来设置。所以Shape::name应该是“形状”,Rectangle::name应该是“矩形”

我所做的是初始化每个 .cpp 实现文件中的静态变量。所以在 Shape.cpp 中:

string Shape::name = "Shape";

在 Rectangle.cpp 中:

string Shape::name = "Rectangle";

链接器不喜欢这样,并抱怨有重复的符号。那么我该如何实现呢?

注意:我想坚持使用带有初始化列表的构造函数(.cpp 中没有实现)

4

2 回答 2

6

你试图做的永远不会奏效。一个static变量只能有一个分配值的声明,而不是您尝试过的不同文件中的两个单独的声明。你想要做的有点类似于试图让两个不同的函数体源于同一个函数头。不起作用,也不应该起作用,重复符号错误。

要使其工作,您需要在类中调用另一个静态变量。派生类变量隐藏了基类中的变量。nameRectanglenamenameShape

然后你只需使用:

string Rectangle::name="Rectangle"

如果不相信,试试这个

#include <stdio.h>
#include <string>
using namespace std ;
struct Base 
{
  static string name ;

  Base(){
    printf( "Base: A %s was created\n", name.c_str() ) ;
  }
} ;

string Base::name="Base";

struct Derived
{
  static string name ;

  Derived(){
    printf( "Derived: A %s was created\n", name.c_str() ) ;
  }
} ;

string Derived::name="Derived";



int main(int argc, const char * argv[])
{
  Base b ;
  Derived d;
}
于 2013-07-09T01:22:17.963 回答
4

您可以尝试制作一个返回名称的虚函数。那可能更干净。我也相信,如果您将名称设为私有,您也可以

于 2013-07-09T01:15:12.363 回答