在向量中具有引用成员的类。 [英] Classes with reference members in a vector.

查看:75
本文介绍了在向量中具有引用成员的类。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我正在尝试制作一个包含对象的向量,并且有一个参考

成员。但是,只要我尝试将一个元素push_back到这个

向量中,g ++就会发现它需要在包含引用的类上实例化一个operator =

这一事实。成员(请参阅下面我尝试的内容

)。


#include< vector>


class TestClass {

private:

const int& m_q;

public:

TestClass(const int& q){m_q = q; }

};


int main()

{

std :: vector< TestClass> ; v;

int hello = 5;

v.push_back(TestClass(你好));

}


我原本预计复制构造函数调用将在

中被执行而不是赋值。


任何人都可以解释如何可以实施所希望的操作(或者为什么我不想让它工作?)。


祝你好运,Sidney

Hi all,

I am trying to make a vector containing objects the have a reference
member. However, as soon as I try to push_back an element into this
vector, g++ balks at the fact that it needs to instantiate an operator=
on the class containing the reference members (see below for what I try
to do).

#include <vector>

class TestClass {
private:
const int & m_q;
public:
TestClass(const int & q) { m_q = q; }
};

int main()
{
std::vector<TestClass> v;
int hello = 5;
v.push_back(TestClass(hello));
}

I would have expected that a copy constructor call would be executed in
the offended line instead of an assignment.

Can anyone explain how the desired operation could be implemented (or
why it doesn''t make sense for me to want it to work?).

Best regards, Sidney

推荐答案

哎呀。在上一封邮件中,请阅读......


TestClass(const int& q):m_q(q){}


。 ...用于构造函数定义。它应该立即

初始化,当然......但问题仍然存在。


Cheerio,


Sidney

Oops. In the previous mail, please read ...

TestClass(const int & q): m_q(q) { }

.... for the constructor definition. It should be immediately
initialized, of course.... But the problem remains.

Cheerio,

Sidney



si **** @ jigsaw .nl 写道:
哎呀。在上一封邮件中,请阅读...

TestClass(const int& q):m_q(q){}

...用于构造函数定义。它应该立即初始化,当然......但问题仍然存在。

Cheerio,

Sidney
Oops. In the previous mail, please read ...

TestClass(const int & q): m_q(q) { }

... for the constructor definition. It should be immediately
initialized, of course.... But the problem remains.

Cheerio,

Sidney




我不认为你可以在STL容器中有引用(比如

Vector)。主要是因为复制时的问题。与

指针不同,引用只能设置一次。


HTH,

Vikram



I dont think you can have references inside a STL container (like
Vector). Mainly because of issues while copying. A reference, unlike a
pointer, can only be set once.

HTH,
Vikram




Vikram写道:

Vikram wrote:
我不认为你可以在STL容器内有引用(比如
矢量)。主要是因为复制时的问题。与
指针不同,引用只能设置一次。
I dont think you can have references inside a STL container (like
Vector). Mainly because of issues while copying. A reference, unlike a
pointer, can only be set once.




这很可能是STL设计决策或限制,我不是

意识到。但请注意,我决不会多次设置一个参考





That could well be an STL design decision or limitation that I am not
aware of. Note, however, that at no point I want to set a reference
more than once.


这篇关于在向量中具有引用成员的类。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆