本文介绍了如何调用标头中声明的main中的类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好ppl.如何从我的object.h头文件间接调用我的类对象到main.cpp文件,因为我不想在main.cpp中声明我的类对象?需要使用哪种指针类型更好?
例如:
Hello ppl. How to call my class object indirect from my object.h header file in to main.cpp file, because i don''t want to declare my class object in main.cpp? Which pointer type is need to use better?
For example:
// object.h
MyClass MyObject(1);
int * pMyObject;
pMyObject = &MyObject;
// class.cpp
#include "class.h"
#include "object.h"
MyClass::MyClass
{
...
}
// class.h
Class MyClass
{
...
};
// main.cpp
#include <iostream>
#include "class.h"
#include "object.h"
int main()
{
MyClass MyObject(1); // I need somehow to point my declaration from header,
// but do not declare in main.cpp
MyObject->setFunc(); MyObject->getFunc();
}
</iostream>
可能吗?有任何想法吗?感谢您的帮助.
Is it possible? Any ideas? Thanks for help.
推荐答案
class MyClass {
public:
MyClass(int value) : m_Value(value) { }
int Value() const { return m_Value; }
int SomeSeriousMethod();
private:
int m_Value;
};
MyClass.cpp :
MyClass.cpp:
#pragma once
#include <stdafx.h> //only if you use pre-compiled headers
#include "MyClass.h"
int MyClass::SomeSeriousMethod() { /*...*/ }
用法:
Usage:
#include "MyClass.h"
//..
void SomeFunction() {
MyClass instanceOnStack(1);
int value1 = instanceOnStack.SomeSeriousMethod();
MyClass * instanceInHeap = new MyClass(2);
int value2 = instanceInHeap->SomeSeriousMethod();
//...
//you can access existing stack instance by pointer as well:
MyClass * someOtherInstance = &instanceOnStack;
value2 = someOtherInstance->SomeSeriousMethod();
//...
//important; better do it under try-finally; this is a "finally" part:
delete instanceInHeap;
}
这篇关于如何调用标头中声明的main中的类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!