override函数的返回值也必须一致

/**结论:派生类override基类的虚函数时,函数的返回值也必须一致。
*/

#include <iostream>
using namespace std;

class CBase
{
public:
	virtual void Func(){ cout<<"CBase::Func()...."<<endl; }
};

class CDerived: public CBase
{
public:
	void Func(){ cout<<"CDerived::Func()...."<<endl; }

	/**下面的override函数的返回值不同导致编译不过:
	*  error C2555: “CDerived::Func”: 重写虚函数返回类型有差异,且不是来自“CBase::Func”的协变
	*/
	//int Func(){ cout<<"CDerived::Func()...."<<endl; return 0; }
};

int main(int argc,char* argv[])
{
	CBase* base = new CDerived();
	base->Func();

	system("pause");
	return 0;
}

在线程中获取函数返回值需要通过线程同步机制来完成,因为通常主线程不会直接等待子线程执行完毕并获取其结果。这里有几个常见的做法: 1. 使用 Future 和 Callable:在 Java 中,你可以将 Runnable 或者Callable 类型的任务封装到 Thread 的目标对象,然后创建一个 Future 对象。Future 提供了 get() 方法,可以阻塞直到任务完成并且获取返回值。 ```java ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new Callable<String>() { @Override public String call() { // 子线程的函数执行代码 return "result"; } }); try { String result = future.get(); // 这里会阻塞直到获取到结果 } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } executor.shutdown(); ``` 2. 自定义同步容器:如果你的线程任务相对简单,也可以考虑自定义一些类来存储结果,并提供一种同步机制(如 synchronized 关键字、Lock 接口等)来读取这个结果。 ```java public class TaskWithResult { private Object result; // ...其他构造方法和方法 // 线程任务完成之后设置结果 public void setResult(Object result) { synchronized (this) { this.result = result; notifyAll(); // 醒醒主线程 } } // 主线程调用此方法来获取结果 public Object getResult() throws InterruptedException { synchronized (this) { while (result == null) { wait(); // 等待结果可用 } return result; } } } // 使用示例 TaskWithResult task = new TaskWithResult(); new Thread(() -> { task.setResult("thread result"); }).start(); Object result = task.getResult(); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值