This question already has answers here:
error: request for member '..' in '..' which is of non-class type

(9个答案)


3年前关闭。




我编写了一个简单的C++程序,如下所示:
#include<iostream>
using namespace std;

class Rectangle
{
    double length, breadth;

public:
    Rectangle(void);        // constructor overloading
    Rectangle(double, double);  // constructor of class
    // void set_values(double l, double b);
    double area(void);
};  // can provide an object name here


// default constructor of class 'Rectangle'-
Rectangle::Rectangle(void)
{
    length = 5;
    breadth = 5;
}


// constructor of class 'Rectangle'-
Rectangle::Rectangle(double l, double b)
{
    length = l;
    breadth = b;
}


/*
void Rectangle::set_values(double l, double b)
{
    length = l;
    breadth = b;
}
*/


double Rectangle::area(void)
{
    return length * breadth;
}


int main()
{
    /*
    Rectangle r;
    r.set_values(12, 3.4);
    */

    Rectangle r(12, 3.4);
    Rectangle s();

    cout<<"Area = "<<r.area()<<endl;
    cout<<"Area = "<<s.area()<<endl;


return 0;
}

当我尝试编译它时,出现以下错误-
Classes_Example.cpp: In function ‘int main()’:
Classes_Example.cpp:61:21: error: request for member ‘area’ in ‘s’, which is of non-class type ‘Rectangle()’
  cout<<"Area = "<<s.area()<<endl;

我正在使用g++(GCC)7.2.0

谢谢!

最佳答案

Rectangle s();

是函数声明而不是变量。在c++中,任何可以解析为函数声明的东西都将对解析进行替代。删除()将使其变为变量。

09-06 16:00