我是C ++的新手,并且对于类如何在C ++中访问另一个类中的公共方法感到困惑。例如,
//.h of class A
class A {
public:
void setDimension (int width, int height);
A* obj;
}
//.cpp of class A
#include "A.h"
void A::setDimension (int width, int height) {
// do some stuffs here
}
//.h of class B
#include "A.h"
class B {
public:
void function ();
//do something here
}
//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
obj->setDimension(int width, int height);
}
现在我希望B类可以访问公共方法" setDimension"在A类中。我认为包含了依赖文件,但是当我运行程序时,我收到一个错误setDimension was not declared in this scope
。如何在B类中调用setDimension方法。非常感谢!
答案 0 :(得分:1)
首先要创建对象A的实例,然后在此实例上调用setDimension。
//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
A myInstance;
myInstance.setDimension(10, 10);
}
或者你需要将方法声明为静态,并且可以在没有实例化的情况下调用它:
//.h of class A
class A {
public:
static void setDimension (int width, int height);
}
//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
A::setDimension(10, 10);
}
如果A类是抽象的:
//.h of class B
#include "A.h"
class B : A {
public:
void function ();
}
//.cpp of class B
#include "A.h"
#include "B.h"
void B::function() {
this->setDimension(10, 10);
}
答案 1 :(得分:0)
你需要创建一个A
(并选择一个特定的宽度和高度,或者从某个地方传递它们),这样你就可以使用它的方法
void B::function() {
A mya;
int mywidth = 10;
int myheight = 20;
mya.setDimension(mywidth, myheight);
}
答案 2 :(得分:0)
您可以将A类中的方法setDimension(int width,int height);
声明为静态。
static void setDimension(int width,int height);
void B::function(){
A::setDimension()
}
使用类名和范围解析运算符::