如何从包含构造函数的类调用函数而不调用构造函数? [英] How to call a function from a class that contains a constructor without calling the constructor?

查看:124
本文介绍了如何从包含构造函数的类调用函数而不调用构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,这可能是一个愚蠢的问题,但有没有办法从一个具有构造函数的类访问函数而不调用它的构造函数?这是一个例子:



我尝试过:



Hello, this may be a silly question but is there a way to access a function from a class that has a constructor in it without calling it's constructor? Here is an example:

What I have tried:

class Point {
private:
	int x, y;
public:
	Point()
	{
		x = 1;
		y = 2;
	}
	void callthis() {
		cout << "I want to call this" << endl;
	}
};

推荐答案

如果我理解你的问题,你可以将函数定义为静态和在没有实例化类的情况下调用它。请查看 C ++类的静态成员 [ ^ ]
If I understand your question correctly, you can define the function as static and call it without instantiating the class. Have a look at Static Members of a C++ Class[^]


如果你不能改变那么类,那么不,你如果没有实例化一个对象(也就是调用构造函数),则无法调用成员函数。
if you can't change then class, then no, you can't call a member function without instantiating an object (aka calling the constructor).


将该函数声明为static的第一个解决方案是正确的,但考虑到你没有对象实例你可以执行这个功能。



我的经验是,静态功能或这样的问题只有一些隐藏的症状像isnt属于这个类或函数的问题根本不是最优的。



所以考虑重新设计这个类和函数。
The first solution that declaring the function as static is correct, but consider that you than have no object instance on that you can perform the function.

My experience is, that a static function or such problem is only the symptom of some more hidden issues like isnt belonging into this class or the functions isnt optimal at all.

So consider redesigning this class and the function.


这篇关于如何从包含构造函数的类调用函数而不调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆