【发布时间】:2021-08-19 11:33:03
【问题描述】:
我正在尝试模拟一些等离子体物理,为此我决定将我的“模拟世界”创建为一个类,在“World.h”文件中定义:
#ifndef _WORLD_H
#define _WORLD_H
class World{
public:
World(int _Nx, double _x0, double _xf); //Constructor prototype
int _Nx; //Number of nodes
double _dx; //Cell width
void setTime(double _dt, int _num_ts);
protected:
double _x0; //System origin
double _xf; //System ending
double _dt = 0; //time step length
int _num_ts; //number of time steps
};
#endif
类原型的实现如下:
#include "World.h"
World::World(int Nx, double x0, double xf)
{
this->_Nx = Nx;
this->_x0 = x0;
this->_xf = xf;
this->_dx = (xf - x0)/(Nx - 1);
//std::cout << Nx;
}
void World::setTime(double dt, int num_ts)
{
this->_dt=dt;
this->_num_ts=num_ts;
}
我遇到的问题是,当我从 main 调用函数“World::setTime(/**/)”时:
int main()
{
//Create computational system
World world(1000, 0.0, 0.1); //(Nx, x0, xm)
World::setTime(world._dx, 10000);
/*CODE*/
return 0;
}
编译器显示消息:
[错误] 不能在没有对象的情况下调用成员函数 'void World::setTime(double, int)'
引用作为参数给出的“int num_ts”的值。问题是什么?它所指的对象是什么?
我正在阅读这篇文章:
cannot call member function without object
但我无法在其中应用解决方案,因为我在课堂上写下了一个构造函数。感谢您的回复!
【问题讨论】:
-
公共标识符不应使用下划线前缀。此外,您的标头和实现之间的命名约定不一致。
-
将
World::setTime(world._dx, 10000);更改为world.setTime( world._dx, 10000 ); -
顺便说一句,
World::setTime(...)语法用于调用static方法或解析虚拟成员(因为 C++ 没有base/super关键字)。 -
#define _WORLD_H该名称保留给语言实现。通过定义它,程序的行为将是未定义的。您应该使用另一个标头守卫。另外,int _Nx参数的名称也是出于同样的原因而保留的。 -
@AliEsquembreKucukalic
what is it reserved for?用于语言实现认为必要的任何目的。通常,标准库的内部名称、语言扩展等。Is the problem in the underscore?是。请参阅保留名称的语言规则。
标签: c++ function class constructor