简体   繁体   English

Cout向量地址

[英]Cout vector addresses

I'm new to this website and a bit new in programming. 我是这个网站的新手,编程方面也有些新手。 I'm using vector for the first time and I want to print content of it but I'm getting addresses instead of normal words. 我第一次使用vector,我想打印它的内容,但是我得到的是地址而不是普通的单词。 I don't know how to do that in other way than this. 除此以外,我不知道该如何做。

My vector: 我的向量:

vector<Component*> vect;

and my code for printing: 和我的打印代码:

void Frame::print() {
    for (int i = 0; i < vect.size(); i++)
        cout << vect[i] << endl;
}

You are storing pointers in your vector. 您将指针存储在向量中。 The value of a pointer is a memory address, therefore you are seeing addresses in your output. 指针的值是一个内存地址,因此您在输出中看到的是地址。 You need to dereference the pointers to access the actual Component objects: 您需要取消引用指针才能访问实际的Component对象:

void Frame::print()
{
    for (int i = 0; i < vect.size(); i++)
    {
        Component *component = vect[i];
        cout << *component << endl; // <-- not the extra '*'
    }
}

In order for this to work, an operator<< overload for Component is also required: 为了使其正常工作,还需要为operator<<重载Component

ostream& operator<<(ostream &out, const Component &comp)
{
    // print comp values to out as needed...
    return out;
}

Recommended reading: 推荐阅读:

Operator overloading 运算符重载

You also need to study up on pointers and references in general. 您还通常需要研究指针和引用。

vect is a vector (aka a lump of contiguous storage) of Component * (aka Component pointers) that is it's a chunk of memory with addresses of other chunks of memory which the compiler will treat as a Component class object. vect是Component *(又称Component指针)的向量(也就是一堆连续存储),它是一块内存,其中包含其他内存块的地址,编译器将其视为Component类对象。 Printing those addresses via cout will just give you a big list of meaningless numbers. 通过cout打印这些地址只会给您一大堆毫无意义的数字。

What I suspect you want to do is probably not store a vector of Component pointers at all and just store a vector of Components. 我怀疑您想做的可能根本不存储组件指针的向量,而只存储组件的向量。 It's frowned upon in C++ these days to store raw pointers unless you know exactly what you are doing. 如今,除非您确切地知道自己在做什么,否则在C ++中存储原始指针已不那么受欢迎了。 If you really do want pointers you should use a vector of std::unique_ptr and std::make_unique. 如果确实需要指针,则应使用std :: unique_ptr和std :: make_unique的向量。

Once you start trying to print Components rather than addresses of them you will most likely see that there is no << operator for Component. 一旦开始尝试打印组件而不是它们的地址,您很可能会看到没有<<运算符。 You will need to write one. 您将需要写一个。 Something like 就像是

std::ostream& operator<<(std::ostream &stream, const Component&component)
{
  stream << component.string_member;
  return stream;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM