简体   繁体   English

类成员函数导致错误“非类类型”

[英]class member function resulting in error “non-class type”

I want to have a simple example class (a box) that has a vector data member that stores the dimensions of the box. 我想有一个简单的示例类(一个框),该类具有一个存储框尺寸的矢量数据成员。 I have attempted to code the class such that a vector can be passed to it as an argument on instantiation. 我试图对类进行编码,以便可以将向量作为实例化的参数传递给它。 There is a simple member function of the class that is intended to give a printout of the dimensions vector. 该类有一个简单的成员函数,旨在提供尺寸矢量的打印输出。 When I attempt to compile, I am presented with an error about requesting the member function saying that the function is of a "non-class type". 当我尝试编译时,出现一个关于请求成员函数的错误,说该函数是“非类类型”。 How should I approach this error? 我应该如何处理这个错误?

#include <iostream>
#include <vector>

using std::cout;
using std::endl;

class Box{
    public:
        Box(
            std::vector<double> dimensions
        );
        void display_dimensions();
    private:
        std::vector<double> m_dimensions;
};

Box::Box(
    std::vector<double> dimensions
    ):
    m_dimensions(dimensions){
    }

void Box::display_dimensions(){
    for(unsigned int i = 0; i < m_dimensions.size(); i++){
        std::cout
            << "element[" << i << "] = " << m_dimensions[i]
            << std::endl;
    }
    std::cout << std::endl;
}

int main(){
    // Create an instance of a box and set its dimensions vector data member.
    Box box_A(
        std::vector<double> dimensions = {78.0, 24.0, 18.0} // dimensions
    );
    // Get the box instance to display its dimensions.
    cout << "dimensions of box_A:" << endl;
    box_A.display_dimensions()
}

This is not how you would call a constructor with an argument: 这不是用参数调用构造函数的方式:

Box box_A(
    std::vector<double> dimensions = {78.0, 24.0, 18.0}
);

You can't call a constructor (or any function) with a variable declaration, you have to move it before the call and pass the variable: 您不能使用变量声明来调用构造函数(或任何函数),而必须在调用之前将其移动并传递变量:

std::vector<double> dimensions = {78.0, 24.0, 18.0};
Box box_A(dimensions);

Or, you could create a temporary variable, using a list initalizer to let the compiler deduce the type: 或者,您可以使用列表初始化器创建临时变量,以使编译器推断类型:

Box box_A({78.0, 24.0, 18.0});

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

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