【问题标题】:Add instance of class in vector在向量中添加类的实例
【发布时间】:2021-07-30 06:51:40
【问题描述】:

我正在尝试制作一个类的静态向量(称为“radsurf”),以便在构造实例时将其附加到向量中。

但我在使用 g++ 编译代码时遇到了一些问题。

它告诉我类的静态向量“没有匹配的调用函数”。

有人可以帮我吗?

树视图:

├── include
│   └── radsurf.h
└── radiacaoapp.cpp

radiacaoapp.cpp:

#include <iostream>
#include <vector>
#include "include/radsurf.h"

using namespace std;

int main(){

    radsurf a(0.1); // creates one instance
    radsurf b(0.5); // creates another instance

    // read the list of "e" parameters of the radsurf instances
    for (radsurf x : radsurf::L) {
        cout << x.e << endl;
    }

    return 0;
}

radsurf.h:

#ifndef RADSURF_H
#define RADSURF_H
#include <vector>

    class radsurf{
        public:
            // "e" parameter - each instance has its own
            float e; 
            // L vector that contains all instances of radsurf classes
            static std::vector<radsurf> L; 
            radsurf(float e){
                // assign constructor argument to the "e" parameter of the instance
                this->e=e;
                // adds the instance to the list
                L.push_back(this);
            }
    };

#endif // RADSURF_H

g++编译器错误:

[chandler@chandler-PC radiacaoapptest]$ g++ radiacaoapp.cpp -o test.bin
In file included from radiacaoapp.cpp:3:
include/radsurf.h: In constructor ‘radsurf::radsurf(float)’:
include/radsurf.h:15:33: error: no matching function for call to ‘std::vector<radsurf>::push_back(radsurf*)’
   15 |                 L.push_back(this);
      |                                 ^

【问题讨论】:

  • 您的向量不存储指针,因此您无法将指针推入其中。您可以推送*this,但这会产生副本。你想用这个来完成什么?
  • 我需要稍后调用在执行中创建的所有实例的所有“e”参数(进行一些计算)

标签: c++ class vector


【解决方案1】:

在 C++ 中,this 关键字是指向当前对象实例的指针。您的std::vector&lt;radsurf&gt;radsurf 对象的向量,而不是指向radsurf 对象的指针(不是radsurf*s)。

静态向量应该改为std::vector&lt;radsurf*&gt;,这意味着它包含一个 radsurf 指针列表。如果您想要一个值向量(我对此表示怀疑),那么您可以改为 L.push_back(*this); 在复制之前取消引用 this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多