【发布时间】:2014-02-13 20:56:37
【问题描述】:
我是 C++ 新用户...
我有一个关于如何声明类“classA”的成员的问题,该成员是另一个类“classB”的对象,知道“classB”有一个接受字符串参数的构造函数(除了默认构造函数)。我在网上做了一些关于这个问题的研究,但是它对帮助我解决我正在处理的问题没有多大帮助。
更具体地说,我想创建一个具有 VideoCapture 对象成员的类(VideoCapture 是一个提供视频流的 openCV 类)。
我的班级有这个原型:
class myClass {
private:
string videoFileName ;
public:
myClass() ;
~myClass() ;
myClass (string videoFileName) ;
// this constructor will be used to initialize myCapture and does other
// things
VideoCapture myCapture (string videoFileName /* : I am not sur what to put here */ ) ;
};
构造函数是:
myClass::myClass (string videoFileName){
VideoCapture myCapture(videoFileName) ;
// here I am trying to initialize myClass' member myCapture BUT
// the combination of this line and the line that declares this
// member in the class' prototype is redundant and causes errors...
// the constructor does other things here... that are ok...
}
我已尽最大努力以最简单的方式揭露我的问题,但我不确定我是否设法...
感谢您的帮助和回答。
L.
【问题讨论】:
-
您的私有成员变量与您的构造函数参数同名。这会让你大吃一惊。
-
@m24p 如果编码正确,则不会。 OP 需要一个初始化列表;变量名在这里无关紧要。
-
如果编码正确,它不会有与构造函数参数同名的成员变量。在这种情况下,没有充分的理由给它们提供完全相同的名称。如果不出意外,它会在代码可维护性方面搞砸你。
-
@m24p 它可能会搞砸你;我和这个委员会的大多数贡献者都没有对此有任何问题。使用相同的名称没有问题,除非您不想使用相同的名称。各有各的。
-
@WhozCraig 见stackoverflow.com/questions/10250016/… 我不会-1 你,但说“大多数[堆栈溢出贡献者] 没有问题”似乎不正确。你有引用支持吗?
标签: c++ class opencv initializer